package org.csy.work.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csy.work.dao.UsersDao;
import org.csy.work.dao.impl.UsersDaoImpl;
import org.csy.work.entity.Users;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author CSY
 * @date 2024-11-27
 */
@WebServlet("/reg.do")
public class RegServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String name = req.getParameter("userName");
        String pwd1 = req.getParameter("pwd1");
        String pwd2 = req.getParameter("pwd2");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");

        UsersDao usersDao = new UsersDaoImpl();

        Users user = usersDao.login(name);
        String message = "";
        if(user != null){
            message = "账号已存在！";
        }else if(!pwd1.equals(pwd2)){
            message = "输入的两次密码不一致！";
        }else{
            user = new Users();
            user.setUsername(name);
            user.setPassword(pwd1);
            user.setPhone(phone);
            user.setEmail(email);
            int n = usersDao.register(user);
            if(n > 0){
                message = "Yes";
            }else{
                message = "注册失败！";
            }
        }
        PrintWriter out = resp.getWriter();

        out.write(message);

        out.flush();
        out.close();
    }
}
